package cl.ccs.migracionbcmc.connection;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import javax.sql.DataSource;

public class ConnectionManager {
    
    public ConnectionManager() {
        super();
    }

    /**
     * @param jndiPath
     * @return
     * @throws Exception
     */
    public static Connection getJNDIConnection(String jndiPath) throws Exception{
        Context initialContext;
        Connection result = null;
        try {

            initialContext = new InitialContext();
            if (initialContext == null) {
                log("JNDI problem. Cannot get InitialContext.");
            }
            DataSource datasource = (DataSource)initialContext.lookup(jndiPath);
            if (datasource != null) {

                result = datasource.getConnection();
            }

        } catch (NamingException e) {
            log(e);
            throw new Exception(e.getMessage());
        } catch (SQLException e) {
            log(e);
            throw new Exception(e.getMessage());
        }
        return result;
    }

    private static void log(Exception aObject) {
        aObject.printStackTrace();
    }

    private static void log(String aObject) {
        System.err.println(aObject);
    }
}
